import React, { Component } from 'react';
import Game from './Game';
// import logo from './logo.svg';
import './App.css';
// import $ from 'jquery';

//All 'handle' in function name alias to 'hd'
//All 'change' in function name alias to 'cg'
class App extends Component {

  constructor(props) {
    super(props)
    this.state = {
      registerName: '',
      registerPass: '',
      registerNick: '',
      loginId: 'kobako',
      loginPass: '123',
      isLoginSuccessful: false,
      player: {},//Initing when Game component finishes mounting
      ws: null//Websockets
    }
  }

  hdLogin = async (e) => {
    e.preventDefault();

    var ws = this.state.ws
    //region MOCK
    if (ws == null || ws.readyState == this.state.ws.CLOSED) {
      ws = await this.initWs()
    }
    ws.mySend({ url: 'login', user: this.state.loginId, pass: this.state.loginPass }, res => {
      if (res.ok) {
        this.setState({ isLoginSuccessful: true })
      } else {
        alert(res.err)
        this.setState({ isLoginSuccessful: false })
      }
    })
    // this.setState({ isLoginSuccessful: true })
    //end MOCK
  }

  initWs = () => {
    return new Promise((resolve, reject) => {
      const me = this

      const ws = new WebSocket("ws://localhost:9000");
      ws.onopen = function () {
        console.log('WS opened!')
        resolve(ws)
      };

      // Log errors
      ws.onerror = function (error) {
        console.log('WebSocket Error ' + error);
        alert('You have lost connect')
        // me.setState({ isLoginSuccessful: false })
      };



      // Exit logined status on closing
      ws.onclose = (e) => {
        console.log('WebSocket Closed ' + e);
        alert('You have lost connect')
        // me.setState({ isLoginSuccessful: false })
      }

      // A custom send function with callback function
      ws.cbs = {}
      ws.mySend = (data, callback) => {
        if (callback != null) {
          if (ws.cbs[data.url] != null) {
            console.warn('WS: You have covered a callback function!')
          }
          ws.cbs[data.url] = callback
        }
        ws.send(JSON.stringify(data))
      }

      // Log messages from the server
      ws.onmessage = function (e) {
        console.log("WS onmessage")
        const data = JSON.parse(e.data)
        console.log(data);
        //Run callback
        if (data.url != null) {
          if(typeof ws.cbs[data.url] === 'function'){
            ws.cbs[data.url](data)
          }else{
            console.warn('WS: url '+data.url+' has not callback!')
          }
        }
      };

      this.setState({ ws })
    })
  }

  setPlayer = player => {
    this.setState({ player })
  }


  hdRegister = async (e) => {
    e.preventDefault();
    const me = this
    var ws = this.state.ws
    if (ws == null || ws.readyState == this.state.ws.CLOSED) {
      ws = await this.initWs()
    }
    ws.mySend({ url: 'register', name: this.state.registerName, pass: this.state.registerPass, nick: this.state.registerNick }, res => {
      if (res.ok) {//Auto Login
        me.setState({
          loginId: this.state.registerName,
          loginPass: this.state.registerPass,
        }, () => {
          me.hdLogin({preventDefault: () => {}})
        })
      } else {
        this.setState({ isLoginSuccessful: false })
      }
    })
  }

  hdcgloginId = ({ target: { value } }) => {
    this.setState({ loginId: value })
  }

  hdcgLoginPass = ({ target: { value } }) => {
    this.setState({ loginPass: value })
  }

  hdcgRegisterName = ({ target: { value } }) => {
    this.setState({ registerName: value })
  }

  hdcgRegisterPass = ({ target: { value } }) => {
    this.setState({ registerPass: value })
  }

  hdcgRegisterNick = ({ target: { value } }) => {
    this.setState({ registerNick: value })
  }

  loginOrRegister = () => {
    return (
      <div>
        {/* Register */}
        <p>Register</p>
        <form onSubmit={this.hdRegister}>
          <label>
            name: <input value={this.state.registerName} onChange={this.hdcgRegisterName}></input> <br />
          </label>
          <label>
            pass: <input value={this.state.registerPass} onChange={this.hdcgRegisterPass}></input> <br />
          </label>
          <label>
            nick: <input value={this.state.registerNick} onChange={this.hdcgRegisterNick}></input> <br />
          </label>
          <input type="submit" value="Submit" />
        </form>


        {/* Login */}
        <p>Login</p>
        <form onSubmit={this.hdLogin}>
          <label>
            name: <input value={this.state.loginId} onChange={this.hdcgloginId}></input> <br />
          </label>
          <label>
            pass: <input value={this.state.loginPass} onChange={this.hdcgLoginPass}></input> <br />
          </label>
          <input type="submit" value="Submit" />
        </form>
      </div>
    )
  }

  render() {
    return (
      <div className="App">
        {this.state.isLoginSuccessful ? (<Game ws={this.state.ws} setPlayer={this.setPlayer} id={this.state.loginId} />) : this.loginOrRegister()}
      </div>
    )
  }
}

export default App;
